/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-12 18:19:45
 */
import { useUserInfoStore } from '@/stores/userInfo'
import axios, { type Method } from 'axios'
import { showFailToast } from 'vant/lib/toast'

// 创建axios实例
const instance = axios.create({
  baseURL: '/mi',
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userInfoStore = useUserInfoStore()

    // 可以判断是否存在，如果存在添加即可
    if (userInfoStore.token && config.headers) {
      config.headers.token = userInfoStore.token
    }

    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 简化响应数据
    const res = response.data
    if (res.code !== 200 && res.code !== 20000) {
      // ② 处理响应的异常
      if (res.code === 20001) {
        showFailToast('token失效,请重新登录')
        const userInfoStore = useUserInfoStore()

        userInfoStore.userInfo.name && location.reload()
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    showFailToast('网络异常，请稍后重试！')
    return Promise.reject(error)
  }
)

// showSuccessToast('成功文案');
// showFailToast('失败文案');

export interface IReqDataRes<T> {
  code: number
  data: T
  message: string
  success: boolean
}

/**
 * @description: 二次封装axios请求
 * @return {*}
 * @param {*} T
 */
const httpMI = <T>(url: string, method: Method, data?: unknown) => {
  const newMeThod = method.toLocaleUpperCase()
  return instance.request<IReqDataRes<T>, IReqDataRes<T>>({
    url,
    method: newMeThod,
    params: newMeThod === 'GET' ? data : {},
    data: newMeThod === 'POST' || newMeThod === 'PUT' || newMeThod === 'DELETE' ? data : {}
  })
}

export { httpMI }
